<template>
    <div class="white-box">
        <el-form ref="ruleNewsRef" :model="ruleNewsForm" :rules="ruleNews" label-width="120px">
            <el-form-item label="文章分类" prop="cate_id">
                <el-select v-model="ruleNewsForm.cate_id" clearable placeholder="请选择文章分类">
                	<el-option :label="item.name" :value="item.cate_id" v-for="(item, index) in class_options"
                		:key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="文章标题" prop="title">
                <el-input v-model.trim="ruleNewsForm.title" clearable placeholder="请输入文章标题" />
            </el-form-item>
            <el-form-item label="文章内容" prop="title">
                <div class="editor-box">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                    <Editor
                        style="height: 440px; overflow-y: hidden"
                        v-model="valueHtml"
                        :defaultConfig="editorConfig"
                        mode="default"
                        @onCreated="handleCreated"
                    />
                </div>
            </el-form-item>
            <el-form-item>
                <div class="foot-btn flexs-center" style="margin-top: 30px">
                    <el-button type="primary" size="large" :loading="form_loading" @click="submitNewsForm(ruleNewsRef)">确认修改</el-button>
                </div>
            </el-form-item>
        </el-form>

        <go-back />
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, CloseBold } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

var eid = route.query.eid || ""

onMounted(() => {
    if (eid) {
        getDetail()
    }
})

// 获取分类  1用户协议，2购物协议，3骑手协议,4隐私协议,5隐私政策
const class_options = ref([
	{
		cate_id:1,
		name:"用户协议"
	},
	{
		cate_id:2,
		name:"购物协议"
	},
	{
		cate_id:3,
		name:"骑手协议"
	},
	{
		cate_id:4,
		name:"隐私协议"
	},
	
	{
		cate_id:6,
		name:"商家协议"
	},
])

function getDetail() {
    proxy.$axios
        .get("admin/setting/agreement/get", {
            params: {
                id: eid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                
                valueHtml.value = result.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
                ruleNewsForm.cate_id = result.is_type
                ruleNewsForm.title = result.title
                
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 添加
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} classType 弹窗类型，1是添加，2是编辑
 * @param {Array} ruleNewsRef 表单规则
 * @param {Object} ruleNewsForm  表单字段
 * @param {Object} ruleNews  表单提示
 * @param {Function} submitNewsForm 提交表单
 */
const form_loading = ref(false)
const ruleNewsRef = ref(null)
const ruleNewsForm = reactive({
    cate_id: "",
    title: "",
})
const ruleNews = reactive({
    cate_id: [{ required: true, message: "请选择文章分类", trigger: "change" }],
    title: [{ required: true, message: "请输入文章名称", trigger: "blur" }],
    
})
const submitNewsForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            let htmls = ""
            if (valueHtml.value) {
                htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
            }

            form_loading.value = true
            proxy.$axios
                .post("admin/agreement/store", {
                    id: eid,
                    is_type: ruleNewsForm.cate_id,
                    title: ruleNewsForm.title,
                    
                    content: htmls,
                })
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({message:"保存成功！",type:"success"})
                        router.push("/NewsList")
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref("") // 内容 HTML
const toolbarConfig = {
    excludeKeys: [
        // 排除不需要的菜单
        "insertLink",
        "insertImage",
        "editImage",
        "viewImageLink",
        "insertVideo",
        "uploadVideo",
        "editVideoSize",
        "emotion",
    ],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义上传
    async customUpload(file, insertFn) {
        let data = new FormData()
        data.append("from", "album")
        data.append("image", file)
        proxy.$axios
            .post("upload/image", data)
            .then((res) => {
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.pic
                    insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
                } else {
                    proxy.$message({message:res.data.msg,type:"error"})
                }
            })
            .catch((err) => {})
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>
<script>
export default {
    name: "NewsEdit",
}
</script>

<style lang="less" scoped>
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}

:deep(.el-date-editor) {
    width: 320px !important;

    .el-input__wrapper {
        width: 320px;
    }
}

.prize-upload {
    :deep(.el-upload--picture-card) {
        width: 120px;
        height: 120px;
        line-height: 120px;
        margin-bottom: 20px;
    }

    :deep(.el-upload-list__item) {
        width: 120px;
        height: 120px;
    }
}
</style>
